

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc] 参考资料 视频链接 运行环境  win10 IDEA专业版 SpringBoot 2.6.2  SpringBoot 自动配置原理 一、Condition Condition 是在 Spring 4.0 增加的条件判断功能，作用是实现选择性的创建Bean操作 思考：SpringBoot是如何知道要创建哪个 Bean的？比如SpringBoot是如何知道要创建 RedisTemplat">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot 笔记3 SpringBoot 自动配置 _ Condition的实现 _ 切换web内置服务器 _ @Enable 注解 _ @Import注解 _自动配置模拟实现">
<meta property="og:url" content="http://example.com/2022/01/08/SpringBoot%20%E7%AC%94%E8%AE%B03%20SpringBoot%20%E8%87%AA%E5%8A%A8%E9%85%8D%E7%BD%AE%20_%20Condition%E7%9A%84%E5%AE%9E%E7%8E%B0%20_%20%E5%88%87%E6%8D%A2web%E5%86%85%E7%BD%AE%E6%9C%8D%E5%8A%A1%E5%99%A8%20_%20@Enable%20%E6%B3%A8%E8%A7%A3%20_%20@Import%E6%B3%A8%E8%A7%A3%20_%E8%87%AA%E5%8A%A8%E9%85%8D%E7%BD%AE%E6%A8%A1%E6%8B%9F%E5%AE%9E%E7%8E%B0/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc] 参考资料 视频链接 运行环境  win10 IDEA专业版 SpringBoot 2.6.2  SpringBoot 自动配置原理 一、Condition Condition 是在 Spring 4.0 增加的条件判断功能，作用是实现选择性的创建Bean操作 思考：SpringBoot是如何知道要创建哪个 Bean的？比如SpringBoot是如何知道要创建 RedisTemplat">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/5edd22722e8444258e2d774ca5a67cf4.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/a3b841876bc44451a3e5478f92677f68.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/91f579f77db643fd8058e9b7411bf936.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/cff3f7f2e9aa4a7dbb7281a6d7f8fd7c.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/23593666fb5345cc8032c876f613d5e9.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/6ceec54c614a4526bb74297e1b3a818b.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/fa87e2d6cc09482a9414a9bcc146ef80.png#pic_center">
<meta property="article:published_time" content="2022-01-08T12:07:23.000Z">
<meta property="article:modified_time" content="2022-08-22T15:48:52.161Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="SpringBoot">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/5edd22722e8444258e2d774ca5a67cf4.png#pic_center">
  
  
  
  <title>SpringBoot 笔记3 SpringBoot 自动配置 _ Condition的实现 _ 切换web内置服务器 _ @Enable 注解 _ @Import注解 _自动配置模拟实现 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="SpringBoot 笔记3 SpringBoot 自动配置 _ Condition的实现 _ 切换web内置服务器 _ @Enable 注解 _ @Import注解 _自动配置模拟实现"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-01-08 20:07" pubdate>
          2022年1月8日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          20k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          169 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">SpringBoot 笔记3 SpringBoot 自动配置 _ Condition的实现 _ 切换web内置服务器 _ @Enable 注解 _ @Import注解 _自动配置模拟实现</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[toc]</p>
<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><hr>
<p><a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1Lq4y1J77x?p=18">视频链接</a></p>
<h1 id="运行环境"><a href="#运行环境" class="headerlink" title="运行环境"></a>运行环境</h1><hr>
<ul>
<li>win10</li>
<li>IDEA专业版</li>
<li>SpringBoot 2.6.2</li>
</ul>
<h1 id="SpringBoot-自动配置原理"><a href="#SpringBoot-自动配置原理" class="headerlink" title="SpringBoot 自动配置原理"></a>SpringBoot 自动配置原理</h1><hr>
<h1 id="一、Condition"><a href="#一、Condition" class="headerlink" title="一、Condition"></a>一、Condition</h1><hr>
<p>Condition 是在 Spring 4.0 增加的条件判断功能，作用是实现选择性的创建Bean操作</p>
<p>思考：<br>SpringBoot是如何知道要创建哪个 Bean的？比如SpringBoot是如何知道要创建 RedisTemplate的？<br>需求：<br>在Spring的IOC容器中有一个User的Bean，现要求</p>
<p><strong>0x001</strong> 导入 Jedis 坐标后，加载该Bean，没导入则不加载</p>
<p>测试的项目结构</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/19a4132c87ad48dc9ae0a262c3239752.png#pic_center">https://img-blog.csdnimg.cn/19a4132c87ad48dc9ae0a262c3239752.png#pic_center</a> &#x3D;50%x)</p>
<p><code>User.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springbootcondition.domain;<br><br><span class="hljs-keyword">import</span> lombok.AllArgsConstructor;<br><span class="hljs-keyword">import</span> lombok.Data;<br><span class="hljs-keyword">import</span> lombok.NoArgsConstructor;<br><br><span class="hljs-meta">@Data</span><br><span class="hljs-meta">@NoArgsConstructor</span><br><span class="hljs-meta">@AllArgsConstructor</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span> &#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> id;<br>    <span class="hljs-keyword">private</span> String username;<br>    <span class="hljs-keyword">private</span> String password;<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>ClassCondition.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springbootcondition.condition;<br><br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Condition;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.ConditionContext;<br><span class="hljs-keyword">import</span> org.springframework.core.type.AnnotatedTypeMetadata;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ClassCondition</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Condition</span> &#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">matches</span><span class="hljs-params">(ConditionContext context, AnnotatedTypeMetadata metadata)</span> &#123;<br><br>        <span class="hljs-comment">// 需求：导入Jedis坐标后创建Bean</span><br>        <span class="hljs-comment">// 思路：判断Redis.clients.jedis.Jedis.class文件是否存在</span><br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">flag</span> <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;<br>        <span class="hljs-keyword">try</span> &#123;<br>            Class&lt;?&gt; cls = Class.forName(<span class="hljs-string">&quot;redis.clients.jedis.Jedis&quot;</span>);<br>        &#125; <span class="hljs-keyword">catch</span> (ClassNotFoundException e) &#123;<br>            e.printStackTrace();<br>            flag = <span class="hljs-literal">false</span>;<br>        &#125;<br>        <span class="hljs-keyword">return</span> flag;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>UserConfig.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springbootcondition.config;<br><br><span class="hljs-keyword">import</span> com.uni.springbootcondition.condition.ClassCondition;<br><span class="hljs-keyword">import</span> com.uni.springbootcondition.domain.User;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Conditional;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;<br><br><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserConfig</span> &#123;<br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-meta">@Conditional(ClassCondition.class)</span><br>    <span class="hljs-keyword">public</span> User <span class="hljs-title function_">user</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">User</span>();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><code>SpringbootConditionApplication.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springbootcondition;<br><br><span class="hljs-keyword">import</span> org.springframework.boot.SpringApplication;<br><span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;<br><span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.data.redis.RedisProperties;<br><span class="hljs-keyword">import</span> org.springframework.context.ConfigurableApplicationContext;<br><br><span class="hljs-meta">@SpringBootApplication</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SpringbootConditionApplication</span> &#123;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br><br>        <span class="hljs-comment">// 启动 SpringBoot的应用，返回 Spring的 IOC容器</span><br>        <span class="hljs-type">ConfigurableApplicationContext</span> <span class="hljs-variable">context</span> <span class="hljs-operator">=</span> SpringApplication.run(SpringbootConditionApplication.class, args);<br><br>        <span class="hljs-type">Object</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> context.getBean(<span class="hljs-string">&quot;user&quot;</span>);<br>        System.out.println(user);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>0x010</strong> 将类的判断定义为动态的。判断哪个字节码文件存在可以动态指定。</p>
<p>项目结构:</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/e46f6afdd747406986d060bcc633307c.png#pic_center">https://img-blog.csdnimg.cn/e46f6afdd747406986d060bcc633307c.png#pic_center</a> &#x3D;50%x)</p>
<p><code>ClassCondition.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springbootcondition.condition;<br><br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Condition;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.ConditionContext;<br><span class="hljs-keyword">import</span> org.springframework.core.type.AnnotatedTypeMetadata;<br><br><span class="hljs-keyword">import</span> java.util.Map;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">ClassCondition</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Condition</span> &#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> context 上下文对象。 用于获取环境， IOC容器，ClassLoader对象</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> metadata 注解元对象。 可以用于获取注解定义的属性值</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">matches</span><span class="hljs-params">(ConditionContext context, AnnotatedTypeMetadata metadata)</span> &#123;<br>        <span class="hljs-comment">// 需求：导入通过注解属性值value指定坐标后创建Bean</span><br>        <span class="hljs-comment">// 思路：获取注解属性值</span><br>        Map&lt;String, Object&gt; map = metadata.getAnnotationAttributes(ConditionOnClass.class.getName());<br>        String[] value = (String[])map.get(<span class="hljs-string">&quot;value&quot;</span>);<br>        <span class="hljs-type">boolean</span> <span class="hljs-variable">flag</span> <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-keyword">for</span> (String className : value) &#123;<br>                Class&lt;?&gt; cls = Class.forName(className);<br>            &#125;<br>        &#125; <span class="hljs-keyword">catch</span> (ClassNotFoundException e) &#123;<br>            e.printStackTrace();<br>            flag = <span class="hljs-literal">false</span>;<br>        &#125;<br>        <span class="hljs-keyword">return</span> flag;<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p><code>ConditionOnClass.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springbootcondition.condition;<br><br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Conditional;<br><br><span class="hljs-keyword">import</span> java.lang.annotation.*;<br><br><br><span class="hljs-meta">@Target(&#123;ElementType.TYPE, ElementType.METHOD&#125;)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-meta">@Documented</span><br><span class="hljs-meta">@Conditional(ClassCondition.class)</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> ConditionOnClass &#123;<br>    String[] value();<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p><code>UserConfig.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springbootcondition.config;<br><br><span class="hljs-keyword">import</span> com.uni.springbootcondition.condition.ClassCondition;<br><span class="hljs-keyword">import</span> com.uni.springbootcondition.condition.ConditionOnClass;<br><span class="hljs-keyword">import</span> com.uni.springbootcondition.domain.User;<br><span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.condition.ConditionalOnClass;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Conditional;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;<br><br><br><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserConfig</span> &#123;<br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-meta">@ConditionOnClass(&quot;redis.clients.jedis.Jedis&quot;)</span><br>    <span class="hljs-keyword">public</span> User <span class="hljs-title function_">user</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">User</span>();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>其实在SpringBoot中，自动实现了之前的需求</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/81f3bc3b36a0484abbd85914230f0aad.png#pic_center">https://img-blog.csdnimg.cn/81f3bc3b36a0484abbd85914230f0aad.png#pic_center</a> &#x3D;60%x)</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/32b896ae1cbc478cb6530bab857b9b50.png#pic_center">https://img-blog.csdnimg.cn/32b896ae1cbc478cb6530bab857b9b50.png#pic_center</a> &#x3D;60%x)</p>
<p>源码：<code>ConditionalOnBean.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">//</span><br><span class="hljs-comment">// Source code recreated from a .class file by IntelliJ IDEA</span><br><span class="hljs-comment">// (powered by FernFlower decompiler)</span><br><span class="hljs-comment">//</span><br><br><span class="hljs-keyword">package</span> org.springframework.boot.autoconfigure.condition;<br><br><span class="hljs-keyword">import</span> java.lang.annotation.Annotation;<br><span class="hljs-keyword">import</span> java.lang.annotation.Documented;<br><span class="hljs-keyword">import</span> java.lang.annotation.ElementType;<br><span class="hljs-keyword">import</span> java.lang.annotation.Retention;<br><span class="hljs-keyword">import</span> java.lang.annotation.RetentionPolicy;<br><span class="hljs-keyword">import</span> java.lang.annotation.Target;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Conditional;<br><br><span class="hljs-meta">@Target(&#123;ElementType.TYPE, ElementType.METHOD&#125;)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-meta">@Documented</span><br><span class="hljs-meta">@Conditional(&#123;OnBeanCondition.class&#125;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> ConditionalOnBean &#123;<br>    Class&lt;?&gt;[] value() <span class="hljs-keyword">default</span> &#123;&#125;;<br><br>    String[] type() <span class="hljs-keyword">default</span> &#123;&#125;;<br><br>    Class&lt;? <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Annotation</span>&gt;[] annotation() <span class="hljs-keyword">default</span> &#123;&#125;;<br><br>    String[] name() <span class="hljs-keyword">default</span> &#123;&#125;;<br><br>    SearchStrategy <span class="hljs-title function_">search</span><span class="hljs-params">()</span> <span class="hljs-keyword">default</span> SearchStrategy.ALL;<br><br>    Class&lt;?&gt;[] parameterizedContainer() <span class="hljs-keyword">default</span> &#123;&#125;;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>当 Spring IOC容器 存在某个Bean时才执行</p>
<p>比如 Redis的自动配置功能，源码<code>org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguraion.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Bean</span><br><span class="hljs-meta">@ConditionalOnMissingBean(</span><br><span class="hljs-meta">    name = &#123;&quot;redisTemplate&quot;&#125;</span><br><span class="hljs-meta">)</span><br><span class="hljs-meta">@ConditionalOnSingleCandidate(RedisConnectionFactory.class)</span><br><span class="hljs-keyword">public</span> RedisTemplate&lt;Object, Object&gt; <span class="hljs-title function_">redisTemplate</span><span class="hljs-params">(RedisConnectionFactory redisConnectionFactory)</span> &#123;<br>    RedisTemplate&lt;Object, Object&gt; template = <span class="hljs-keyword">new</span> <span class="hljs-title class_">RedisTemplate</span>();<br>    template.setConnectionFactory(redisConnectionFactory);<br>    <span class="hljs-keyword">return</span> template;<br>&#125;<br><br><span class="hljs-meta">@Bean</span><br><span class="hljs-meta">@ConditionalOnMissingBean</span><br><span class="hljs-meta">@ConditionalOnSingleCandidate(RedisConnectionFactory.class)</span><br><span class="hljs-keyword">public</span> StringRedisTemplate <span class="hljs-title function_">stringRedisTemplate</span><span class="hljs-params">(RedisConnectionFactory redisConnectionFactory)</span> &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">StringRedisTemplate</span>(redisConnectionFactory);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>@ConditionalOnMissingBean表示当某个Bean不存在时，源码中第3行，将name属性值指定为<code>redisTemplate</code></p>
<p>在第13行也有用到，就是不存在的话就创建一个Redis实例，通过使用注解实现对Bean是否存在的判断，若不存在就进行创建对象的处理，从而实现了自动配置</p>
<p><strong>0x011</strong> 小结</p>
<ul>
<li><p>自定义条件</p>
<ul>
<li>定义条件类：自定义实现 Condition 接口，重写 matches 方法， 在matches方法中进行逻辑判断，返回boolean值。 matches方法的两个参数：1) context：上下文对象，可以获取属性值，获取类加载器，获取BeanFactory等；2) metada：元数据对象，用于获取注解属性</li>
<li>判断条件：在初始化Bean时，使用<code>@Conditional（条件类.class) </code>注解</li>
</ul>
</li>
<li><p>SpringBoot 提供的常用条件注解</p>
<table>
<thead>
<tr>
<th>注解名</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td>ConditionalOnProperty</td>
<td>判断配置文件中是否有对应属性和值才初始化Bean</td>
</tr>
<tr>
<td>ConditionalOnClass</td>
<td>判断环境中是否有对应字节码文件才初始化Bean</td>
</tr>
<tr>
<td>ConditionalOnMissingBean</td>
<td>判断环境中没有对应Bean才初始化Bean</td>
</tr>
</tbody></table>
</li>
</ul>
<h1 id="二、切换内置web服务器"><a href="#二、切换内置web服务器" class="headerlink" title="二、切换内置web服务器"></a>二、切换内置web服务器</h1><hr>
<p>源码位置：<code>org.springframework.boot.autoconfigure.web.embedded</code></p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/8ac45551e8e64b37b08ec70c99278d1f.png#pic_center">https://img-blog.csdnimg.cn/8ac45551e8e64b37b08ec70c99278d1f.png#pic_center</a> &#x3D;80%x)</p>
<p><code>EmbeddedWebServerFactoryCustomizerAutoConfiguration.java</code> 源码中自动配置Tomcat部署的实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@ConditionalOnClass(&#123;Tomcat.class, UpgradeProtocol.class&#125;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">TomcatWebServerFactoryCustomizerConfiguration</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">TomcatWebServerFactoryCustomizerConfiguration</span><span class="hljs-params">()</span> &#123;<br>    &#125;<br><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> TomcatWebServerFactoryCustomizer <span class="hljs-title function_">tomcatWebServerFactoryCustomizer</span><span class="hljs-params">(Environment environment, ServerProperties serverProperties)</span> &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">TomcatWebServerFactoryCustomizer</span>(environment, serverProperties);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>可以观察到它用到了 @ConditionalOnClass 注解，就是当存在Tomcat的类还有另外一个UpgradeProtocol的类才会进行配置，其他的几个部署模式也是这样的。</p>
<p>所以在SpringBoot中切换内置web服务器，只需要修改<code>pom.xml </code>中的依赖，排除默认的Tomcat包，添加其他的包比如Jetty，就完成了。</p>
<p><code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-comment">&lt;!-- 排除 Tomcat 依赖 --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">exclusions</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">exclusion</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-tomcat<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">exclusion</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">exclusions</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><span class="hljs-comment">&lt;!-- 引入 Jetty的 依赖 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-jetty<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>开启SpringBoot后，通过查看启动信息可以发现，内置的web服务器切换成功</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/306190ba43ed462f8102d17ed85b78ee.png#pic_center">https://img-blog.csdnimg.cn/306190ba43ed462f8102d17ed85b78ee.png#pic_center</a> &#x3D;80%x)</p>
<h1 id="三、Enable-注解"><a href="#三、Enable-注解" class="headerlink" title="三、Enable*注解"></a>三、Enable*注解</h1><hr>
<p>SpringBoot 提供了很多 Enable开头的注解，这些注解都是用于动态启动某些功能的。而其底层原理是使用@Import注解导入一些配置类，实现Bean的动态加载。</p>
<p>思考：SpringBoot工程是否可以直接获取Jar包中定义的Bean？</p>
<p>测试的项目结构<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/eba4ba372bd64001b6473637dcfe598d.png#pic_center">https://img-blog.csdnimg.cn/eba4ba372bd64001b6473637dcfe598d.png#pic_center</a> &#x3D;80%x)</p>
<p>其中 springboot-enable-other用于模拟其他jar包，先在其放到enable项目内部，类似于给项目导入jar包，然后在到外面的SpringBoot项目里获取里面项目的Bean，测试看看能否获取到。</p>
<p><code>UserConfig.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.domain;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span> &#123;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p><code>EnableUser.java</code> 模拟一个EnableUser注解，用于导入第三方包User的Bean</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.config;<br><br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Import;<br><br><span class="hljs-keyword">import</span> java.lang.annotation.*;<br><br><br><span class="hljs-meta">@Target(&#123;ElementType.TYPE&#125;)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-meta">@Documented</span><br><span class="hljs-meta">@Import(UserConfig.class)</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> EnableUser &#123;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p><code>SpringBootEnableAction.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springbootenable;<br><br><span class="hljs-keyword">import</span> com.uni.config.EnableUser;<br><span class="hljs-keyword">import</span> com.uni.config.UserConfig;<br><span class="hljs-keyword">import</span> org.springframework.boot.SpringApplication;<br><span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;<br><span class="hljs-keyword">import</span> org.springframework.context.ConfigurableApplicationContext;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.ComponentScan;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Import;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * <span class="hljs-doctag">@ComponentScan</span> 扫描范围：当前引导类所在及其子包</span><br><span class="hljs-comment"> * 1. 使用 <span class="hljs-doctag">@ComponentScan</span> 扫描 com.uni.config包</span><br><span class="hljs-comment"> * 2. 使用 <span class="hljs-doctag">@Import</span> 注解，加载类，这些类都会被 Spring创建，并放入IOC容器</span><br><span class="hljs-comment"> * 3. 可以对 <span class="hljs-doctag">@Import</span>注解进行封装</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@SpringBootApplication</span><br><span class="hljs-comment">//@ComponentScan(&quot;com.uni.config&quot;)</span><br><span class="hljs-comment">//@Import(UserConfig.class)</span><br><span class="hljs-meta">@EnableUser</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SpringbootEnableApplication</span> &#123;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">ConfigurableApplicationContext</span> <span class="hljs-variable">context</span> <span class="hljs-operator">=</span> SpringApplication.run(SpringbootEnableApplication.class, args);<br><br>        <span class="hljs-comment">// 获取 Bean</span><br>        <span class="hljs-type">Object</span> <span class="hljs-variable">user</span> <span class="hljs-operator">=</span> context.getBean(<span class="hljs-string">&quot;user&quot;</span>);<br>        System.out.println(user);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>在@SpringBootApplication注解的源码中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Target(&#123;ElementType.TYPE&#125;)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-meta">@Documented</span><br><span class="hljs-meta">@Inherited</span><br><span class="hljs-meta">@SpringBootConfiguration</span><br><span class="hljs-meta">@EnableAutoConfiguration</span><br><span class="hljs-meta">@ComponentScan(</span><br><span class="hljs-meta">    excludeFilters = &#123;@Filter(</span><br><span class="hljs-meta">    type = FilterType.CUSTOM,</span><br><span class="hljs-meta">    classes = &#123;TypeExcludeFilter.class&#125;</span><br><span class="hljs-meta">), @Filter(</span><br><span class="hljs-meta">    type = FilterType.CUSTOM,</span><br><span class="hljs-meta">    classes = &#123;AutoConfigurationExcludeFilter.class&#125;</span><br><span class="hljs-meta">)&#125;</span><br></code></pre></td></tr></table></figure>

<p>其中的 @EnableAutoConfiguration 则实现了自动配置</p>
<p>这体现了之前 能直接获取 redisTemplate Bean的原因，在pom.xml中导入 redis后，改包提供了类似于之前手写的@EnableUser注解，注解中用到了@Import注解，直接将类注入到了Spring的IOC容器，从而使得SpringBoot能识别到对应的类</p>
<h1 id="四、Import-注解"><a href="#四、Import-注解" class="headerlink" title="四、Import 注解"></a>四、Import 注解</h1><hr>
<p>@Enable*底层依赖于 @Import注解导入一些类 ，使用@Import导入的类会被Spring加载到IOC容器中。而@Import提供四种用法</p>
<p>测试的项目结构：</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/8ffaaad826a2467985f6ed278220442f.png#pic_center">https://img-blog.csdnimg.cn/8ffaaad826a2467985f6ed278220442f.png#pic_center</a> &#x3D;50%x)</p>
<p><code>EnableUser.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.config;<br><br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Import;<br><br><span class="hljs-keyword">import</span> java.lang.annotation.*;<br><br><span class="hljs-meta">@Target(&#123;ElementType.TYPE&#125;)</span><br><span class="hljs-meta">@Retention(RetentionPolicy.RUNTIME)</span><br><span class="hljs-meta">@Documented</span><br><span class="hljs-meta">@Import(UserConfig.class)</span><br><span class="hljs-keyword">public</span> <span class="hljs-meta">@interface</span> EnableUser &#123;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><code>MyImportBeanDefinationRegister.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.config;<br><br><span class="hljs-keyword">import</span> com.uni.domain.User;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.support.AbstractBeanDefinition;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.support.BeanDefinitionBuilder;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.support.BeanDefinitionRegistry;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.ImportBeanDefinitionRegistrar;<br><span class="hljs-keyword">import</span> org.springframework.core.type.AnnotationMetadata;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyImportBeanDefinitionRegistrar</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">ImportBeanDefinitionRegistrar</span> &#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">registerBeanDefinitions</span><span class="hljs-params">(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry)</span> &#123;<br>        <span class="hljs-type">AbstractBeanDefinition</span> <span class="hljs-variable">beanDefinition</span> <span class="hljs-operator">=</span> BeanDefinitionBuilder.rootBeanDefinition(User.class).getBeanDefinition();<br>        registry.registerBeanDefinition(<span class="hljs-string">&quot;user&quot;</span>, beanDefinition);<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p><code>MyImportSelector.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.config;<br><br><span class="hljs-keyword">import</span> org.springframework.context.annotation.ImportSelector;<br><span class="hljs-keyword">import</span> org.springframework.core.type.AnnotationMetadata;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">MyImportSelector</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">ImportSelector</span> &#123;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> String[] selectImports(AnnotationMetadata importingClassMetadata) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>[]&#123;<span class="hljs-string">&quot;com.uni.domain.User&quot;</span>, <span class="hljs-string">&quot;com.uni.domain.Role&quot;</span>&#125;;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>UserConfig.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.config;<br><br><span class="hljs-keyword">import</span> com.uni.domain.Role;<br><span class="hljs-keyword">import</span> com.uni.domain.User;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;<br><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UserConfig</span> &#123;<br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> User <span class="hljs-title function_">user</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">User</span>();<br>    &#125;<br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> Role <span class="hljs-title function_">role</span><span class="hljs-params">()</span>&#123;<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Role</span>();&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><code>SpringbootEnableApplication.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springbootenable;<br><br><span class="hljs-keyword">import</span> com.uni.config.EnableUser;<br><span class="hljs-keyword">import</span> com.uni.config.MyImportBeanDefinitionRegistrar;<br><span class="hljs-keyword">import</span> com.uni.config.MyImportSelector;<br><span class="hljs-keyword">import</span> com.uni.config.UserConfig;<br><span class="hljs-keyword">import</span> com.uni.domain.Role;<br><span class="hljs-keyword">import</span> com.uni.domain.User;<br><span class="hljs-keyword">import</span> org.springframework.boot.SpringApplication;<br><span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;<br><span class="hljs-keyword">import</span> org.springframework.context.ConfigurableApplicationContext;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.ComponentScan;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Import;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.ImportSelector;<br><br><span class="hljs-keyword">import</span> java.util.Map;<br><br><span class="hljs-comment">/**</span><br><span class="hljs-comment"> * Import 四种用法</span><br><span class="hljs-comment"> * 1. 导入Bean</span><br><span class="hljs-comment"> * 2. 导入配置类</span><br><span class="hljs-comment"> * 3. 导入ImportSelector的实现类</span><br><span class="hljs-comment"> * 4. 导入ImportBeanDefinitionRegistrar 类</span><br><span class="hljs-comment"> */</span><br><span class="hljs-meta">@SpringBootApplication</span><br><span class="hljs-comment">//@Import(User.class)</span><br><span class="hljs-comment">//@Import(MyImportSelector.class)</span><br><span class="hljs-meta">@Import(MyImportBeanDefinitionRegistrar.class)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SpringbootEnableApplication</span> &#123;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">ConfigurableApplicationContext</span> <span class="hljs-variable">context</span> <span class="hljs-operator">=</span> SpringApplication.run(SpringbootEnableApplication.class, args);<br><br>        <span class="hljs-comment">// 第一种方法的测试</span><br><br><span class="hljs-comment">//        User user = context.getBean(User.class);</span><br><span class="hljs-comment">//        System.out.println(user);</span><br><span class="hljs-comment">//        Map&lt;String, User&gt; map = context.getBeansOfType(User.class);</span><br><span class="hljs-comment">//        System.out.println(map);</span><br><br>        <span class="hljs-comment">// 第二、三种方法的测试</span><br><br><span class="hljs-comment">//        User user = context.getBean(User.class);</span><br><span class="hljs-comment">//        Role role = context.getBean(Role.class);</span><br><span class="hljs-comment">//        System.out.println(user + &quot;\n&quot; + role);</span><br><br>        <span class="hljs-comment">// 第四种方法的测试</span><br>        System.out.println(context.getBean(User.class));<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>@Import 注解的四种用法</p>
<ul>
<li>导入Bean</li>
<li>导入配置类</li>
<li>导入ImportSelector的实现类</li>
<li>导入ImportBeanDefinitionRegistrar 类</li>
</ul>
<p>SpringBoot启动类注解 @SpringBootApplication 是通过上面来实现导入其他类的，步骤依次为：</p>
<ul>
<li><p>@SpringBootApplication </p>
</li>
<li><p>@EnableAutoConfiguration </p>
</li>
<li><p>@Import(AutoConfigurationImportSelector.class) </p>
</li>
<li><p>interface DeferredImportSelector extends ImportSelector</p>
</li>
</ul>
<h1 id="五、-EnableAutoConfiguration-注解"><a href="#五、-EnableAutoConfiguration-注解" class="headerlink" title="五、@EnableAutoConfiguration 注解"></a>五、@EnableAutoConfiguration 注解</h1><hr>
<ul>
<li>@EnableAutoConfiguration 注解内部使用 @import(AutoConfigurationImportSelector.class) 来加载配置类</li>
<li>配置文件位置：<code>META-INF/spring.factories</code>, 改配置文件中定义了大量的配置类，当SpringBoot应用启动时，会自动加载这些配置类，初始化Bean</li>
</ul>
<p>一层一层地查找源码：</p>
<p><img src="https://img-blog.csdnimg.cn/5edd22722e8444258e2d774ca5a67cf4.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><img src="https://img-blog.csdnimg.cn/a3b841876bc44451a3e5478f92677f68.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"><br><img src="https://img-blog.csdnimg.cn/91f579f77db643fd8058e9b7411bf936.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><img src="https://img-blog.csdnimg.cn/cff3f7f2e9aa4a7dbb7281a6d7f8fd7c.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>通过源码的提示可以看到，自动加载类的配置文件在  <code>META-INF/spring.factories</code>的位置，现在找到<code>org.springframework.boot.autoconfigure</code>中的<code>spring-boot-autoconfigure-2.5.6.jar</code> 可以找到存在 META-INF文件夹，而里面就有一个  <code>spring.factories</code>的文件，如下图</p>
<p>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/514ac90ac2f54c38b15600d4cf1fafd7.png#pic_center">https://img-blog.csdnimg.cn/514ac90ac2f54c38b15600d4cf1fafd7.png#pic_center</a> &#x3D;50%x)</p>
<p><code>spring.factories</code>部分内容如下</p>
<p><img src="https://img-blog.csdnimg.cn/23593666fb5345cc8032c876f613d5e9.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>可以发现它包含了Redis类，从而就加载到了容器中，这就是为什么SpringBoot可以直接获取到redisTemplate的原因</p>
<h1 id="六、案例"><a href="#六、案例" class="headerlink" title="六、案例"></a>六、案例</h1><hr>
<p>需求：自定义 redis-starter。 要求当导入 redis坐标时，SpringBoot自动创建Jedis的Bean</p>
<p>导入 MyBatis起步依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.mybatis.spring.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mybatis-spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.3.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>观察原生的jar包实现，里面会提供具体的自动配置类，以及供SpringBoot扫描的spring.factories</p>
<p><img src="https://img-blog.csdnimg.cn/6ceec54c614a4526bb74297e1b3a818b.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>实现步骤：</p>
<ol>
<li>创建 <code>redis-spring-boot-autoconfigure </code>模块</li>
<li>创建 <code>redis-spring-boot-starter</code>模块， 依赖 <code>redis-spring-boot-autoconfigure</code>的模块</li>
<li>在 <code>redis-spring-boot-autoconfigure</code> 模块中初始化 Jedis 的 Bean。并定义 <code>META-INF/spring.factories</code>文件</li>
<li>在测试模块中引入自定义的redis-starer依赖，测试获取Jedis的Bean，操作Redis</li>
</ol>
<p>项目结构<br>![在这里插入图片描述](<a target="_blank" rel="noopener" href="https://img-blog.csdnimg.cn/1e878c99503940d787089c17d076c3a5.png#pic_center">https://img-blog.csdnimg.cn/1e878c99503940d787089c17d076c3a5.png#pic_center</a> &#x3D;50%x)</p>
<p>在负责起步依赖的<strong>redis-spring-boot-starter</strong>模块中，只负责在pom.xml里添加confguration模块的依赖（注：该模块的test类需删除，否则会报错）</p>
<p><code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br>    <span class="hljs-comment">&lt;!-- 引入 configuation --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.uni<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>redis-spring-boot-configuration<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>在 <strong>redis-spring-boot-configuration</strong>模块中，负责配置 jedis 模拟 Redis的自动配置（注：该模块的test类需删除，否则会报错）</p>
<p><code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br>    <span class="hljs-comment">&lt;!-- 添加 Jedis 依赖 --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>redis.clients<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>jedis<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span><br></code></pre></td></tr></table></figure>



<p><code>RedisProperties.java</code> 用于Redis连接的配置实体类，将作为Bean注入到Spring 容器中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.redis.config;<br><br><span class="hljs-keyword">import</span> org.springframework.boot.context.properties.ConfigurationProperties;<br><br><br><span class="hljs-meta">@ConfigurationProperties(prefix=&quot;redis&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">RedisProperties</span> &#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-type">String</span> <span class="hljs-variable">host</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;localhost&quot;</span>;<br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> <span class="hljs-variable">port</span> <span class="hljs-operator">=</span> <span class="hljs-number">6379</span>;<br><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">getHost</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> host;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setHost</span><span class="hljs-params">(String host)</span> &#123;<br>        <span class="hljs-built_in">this</span>.host = host;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">getPort</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> port;<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setPort</span><span class="hljs-params">(<span class="hljs-type">int</span> port)</span> &#123;<br>        <span class="hljs-built_in">this</span>.port = port;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>RedisAutoConfiguration.java</code>  根据之前注入的redisProperties配置Bean来创建一个Jedis Bean 并注入到容器中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.redis.config;<br><br><span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.condition.ConditionalOnClass;<br><span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;<br><span class="hljs-keyword">import</span> org.springframework.boot.context.properties.EnableConfigurationProperties;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;<br><span class="hljs-keyword">import</span> redis.clients.jedis.Jedis;<br><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-meta">@EnableConfigurationProperties(RedisProperties.class)</span><br><span class="hljs-meta">@ConditionalOnClass(Jedis.class)</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">RedisAutoConfiguration</span> &#123;<br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-meta">@ConditionalOnMissingBean(name = &quot;jedis&quot;)</span><br>    <span class="hljs-keyword">public</span> Jedis <span class="hljs-title function_">jedis</span><span class="hljs-params">(RedisProperties redisProperties)</span>&#123;<br>        System.out.println(<span class="hljs-string">&quot;RedisAutoConfiguration...&quot;</span>);<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Jedis</span>(redisProperties.getHost(), redisProperties.getPort());<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>根据之前的源码查找，在声明自动配置类后，需要在resources&#x2F;META-INF下创建一个<code>spring.factories</code>配置文件，用于声明实现了自动扫描的配置类</p>
<p><code>spring.factories</code></p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs stylus">org<span class="hljs-selector-class">.springframework</span><span class="hljs-selector-class">.boot</span><span class="hljs-selector-class">.autoconfigure</span>.EnableAutoConfiguration=\<br>  com<span class="hljs-selector-class">.uni</span><span class="hljs-selector-class">.redis</span><span class="hljs-selector-class">.config</span>.RedisAutoConfiguration<br></code></pre></td></tr></table></figure>

<p>至此，已完成了模拟Redis自动配置的模块，现在到另一个SpringBoot模块中，引入实现的<code>redis-spring-boot-starter</code>起步依赖</p>
<p><code>pom.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br>    <span class="hljs-comment">&lt;!-- 自定义的 Redis的starter --&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.uni<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>redis-spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span><br><br></code></pre></td></tr></table></figure>



<p><code>SpringbootTestApplication.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.uni.springboottest;<br><br><span class="hljs-keyword">import</span> org.springframework.boot.SpringApplication;<br><span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;<br><span class="hljs-keyword">import</span> org.springframework.context.ConfigurableApplicationContext;<br><span class="hljs-keyword">import</span> redis.clients.jedis.Jedis;<br><br><span class="hljs-meta">@SpringBootApplication</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SpringbootTestApplication</span> &#123;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">ConfigurableApplicationContext</span> <span class="hljs-variable">context</span> <span class="hljs-operator">=</span> SpringApplication.run(SpringbootTestApplication.class, args);<br>        <span class="hljs-type">Jedis</span> <span class="hljs-variable">jedis</span> <span class="hljs-operator">=</span> context.getBean(Jedis.class);<br>        jedis.set(<span class="hljs-string">&quot;role&quot;</span>, <span class="hljs-string">&quot;uni&quot;</span>);<br>        <span class="hljs-type">String</span> <span class="hljs-variable">role</span> <span class="hljs-operator">=</span> jedis.get(<span class="hljs-string">&quot;role&quot;</span>);<br>        System.out.println(role);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>测试结果：</p>
<p><img src="https://img-blog.csdnimg.cn/fa87e2d6cc09482a9414a9bcc146ef80.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<h1 id="七、收获与总结"><a href="#七、收获与总结" class="headerlink" title="七、收获与总结"></a>七、收获与总结</h1><hr>
<p>又一次温习了SpringBoot是提供了快速开发Spring项目的作用而不是增强功能。</p>
<p>本次写了好几个Demo，跟着视频教程，使用注解去实现Bean的注入，以及起步依赖之类的，最主要的还是第一次查看了SpringBoot启动类的注解，了解到里面自动配置的一些机制，第一次了解到可以将类作为参数传给一个注解。</p>
<p>本次内容比较多，目前笔者没有完全吸收，不过笔者觉得这一次的学习能有助于SpringBoot的使用，至少在将来写项目的时候，可以配置好依赖。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/SpringBoot/" class="category-chain-item">SpringBoot</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/SpringBoot/">#SpringBoot</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>SpringBoot 笔记3 SpringBoot 自动配置 _ Condition的实现 _ 切换web内置服务器 _ @Enable 注解 _ @Import注解 _自动配置模拟实现</div>
      <div>http://example.com/2022/01/08/SpringBoot 笔记3 SpringBoot 自动配置 _ Condition的实现 _ 切换web内置服务器 _ @Enable 注解 _ @Import注解 _自动配置模拟实现/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年1月8日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/01/12/SpringBoot%20%E7%AC%94%E8%AE%B04%20SpringBoot%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%20_%20%E5%9B%9B%E4%B8%AA%E7%9B%91%E5%90%AC%E6%9C%BA%E5%88%B6%20_%20%E9%80%9A%E8%BF%87%E6%96%AD%E7%82%B9%E8%B0%83%E8%AF%95%E8%BF%9B%E8%A1%8C%E5%8E%9F%E7%90%86%E5%88%86%E6%9E%90%20_%20Admin%E7%9B%91%E6%8E%A7%E6%9C%BA%E5%88%B6%E7%9A%84%E8%BF%90%E7%94%A8%20_%20SpringBoot%E9%83%A8%E7%BD%B2%E6%A8%A1%E5%BC%8F%E5%88%87%E6%8D%A2jar%E4%B8%8Ewar/" title="SpringBoot 笔记4 SpringBoot原理分析 _ 四个监听机制 _ 通过断点调试进行原理分析 _ Admin监控机制的运用 _ SpringBoot部署模式切换jar与war">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">SpringBoot 笔记4 SpringBoot原理分析 _ 四个监听机制 _ 通过断点调试进行原理分析 _ Admin监控机制的运用 _ SpringBoot部署模式切换jar与war</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/01/07/SpringBoot%20%E7%AC%94%E8%AE%B02%20SpringBoot%E6%95%B4%E5%90%88Junit%E6%A1%86%E6%9E%B6%20_%20%E6%95%B4%E5%90%88Redis%20_%20%E6%95%B4%E5%90%88MyBatis%20_%20%E5%85%A5%E9%97%A8Demo/" title="SpringBoot 笔记2 SpringBoot整合Junit框架 _ 整合Redis _ 整合MyBatis _ 入门Demo">
                        <span class="hidden-mobile">SpringBoot 笔记2 SpringBoot整合Junit框架 _ 整合Redis _ 整合MyBatis _ 入门Demo</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
